import json
from datetime import datetime

from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from empapp.models import Employee


# Create your views here.
@csrf_exempt
def add_employee(request):
    data=json.loads(request.body)
    a=Employee.objects.create(
        name=data['name'],
        department=data['department'],
        satary=data['satary'],
        position=data['position'],
        hire_data=datetime.now(),
        status=data['status']
    )
    return JsonResponse(
        {
            'msg':'添加成功',
            'data':model_to_dict(a)
        }
    )
def list_employee(request):
    data=Employee.objects.all()
    page=request.GET.get('page',1)
    size=request.GET.get('size') or 10
    status=request.GET.get('status')
    department=request.GET.get('status')
    if status:
        data=Employee.objects.get(status=status)
    if department:
        data=Employee.objects.get(department=department)
    data=Paginator(data,size).get_page(page)
    total=len(data)
    l=[]
    for i in data:
       l.append(
           {
               'id':i.id,
               'name':i.name,
               'department':i.department,
               'satary':i.satary,
               'position':i.position,
               'hire_data':i.hire_data,
               'status':i.status
           }
       )
    return JsonResponse(
        {
            'msg':'查询成功',
            'item':l,
            'total':total
        }
    )
@csrf_exempt
def update_employee(request,id=None):
    if id==None:
        return JsonResponse(
            {
                'msg':'id必填'
            }
        )
    data=json.loads(request.body)
    u=Employee.objects.get(id=id)
    u.satary=data['satary']
    u.position=data['position']
    u.save()
    return JsonResponse(
        {
            'msg':'修改成功'
        }
    )
@csrf_exempt
def post_employee(request,id=None):
    if id==None:
        return JsonResponse(
            {
                'msg':'id必填'
            }
        )
    data=json.loads(request.body)
    u=Employee.objects.get(id=id)
    u.status=data['status']
    u.save()
    return JsonResponse(
        {
            'msg':'离职成功',
            'data':model_to_dict(u)
        }
    )
